<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="openAddForm">添加商品</el-button>
        </el-col>
      </el-row>
      <!-- 表格数据 -->
      <el-table :data="goodsList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="productName"></el-table-column>
        <el-table-column
          label="商品价格(元)"
          prop="price"
          width="100px"
        ></el-table-column>
        <el-table-column
          label="商品重量（kg）"
          prop="weight"
          width="90px"
        ></el-table-column>
        <el-table-column
          label="商品数量"
          prop="numbers"
          width="80px"
        ></el-table-column>
        <el-table-column label="所属分类" width="130px">
          <template slot-scope="scope">
            <el-tooltip content="点击查看供应商信息" placement="top">
              <el-button @click="getProvider(scope.row.productName)">
                {{ scope.row.category }}</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="date" width="160px">
          <template slot-scope="scope">{{
            scope.row.date | dataFormat
          }}</template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.productId)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </el-card>
    <!-- 添加商品的对话框 -->
    <el-dialog
      title="添加商品"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="addDialogClosed"
    >
      <!-- 内容区 -->
      <el-form
        :model="addForm"
        :rules="productRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="商品名称" prop="productName" label-width="80px">
          <el-select
            v-model="addForm.productName"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in providersList"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price" label-width="80px">
          <el-input v-model="addForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category" label-width="80px">
          <el-select v-model="addForm.category" filterable placeholder="请选择">
            <el-option
              v-for="item in parentCateList"
              :key="item.cate_id"
              :label="item.cate_name"
              :value="item.cate_name"
            >
            </el-option>
          </el-select>
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            style="margin-left:30px"
            @click="addCateDialogVisible = true"
            >新增分类</el-button
          >
        </el-form-item>
        <el-form-item label="商品数量" prop="numbers" label-width="80px">
          <el-input v-model.number="addForm.numbers"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="weight" label-width="80px">
          <el-input v-model="addForm.weight"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addProduct"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="70%"
      @close="addDialogClosed"
    >
      <!-- 添加分类表单 -->
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cate_name">
          <el-input v-model="addCateForm.cate_name"></el-input>
        </el-form-item>
        <el-form-item label="分类ID：" prop="cate_id">
          <el-input v-model.number="addCateForm.cate_id"></el-input>
        </el-form-item>
        <el-form-item label="分类备注：" prop="cate_remark">
          <el-input v-model="addCateForm.cate_remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改商品的对话框 -->
    <el-dialog
      title="修改商品信息"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <!-- 内容区 -->
      <el-form
        :model="editForm"
        :rules="productRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="商品名称" prop="productName" label-width="80px">
          <el-input v-model="editForm.productName" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price" label-width="80px">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category" label-width="80px">
          <el-select
            v-model="editForm.category"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in parentCateList"
              :key="item.cate_id"
              :label="item.cate_name"
              :value="item.cate_name"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品数量" prop="numbers" label-width="80px">
          <el-input v-model.number="editForm.numbers"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="weight" label-width="80px">
          <el-input v-model="editForm.weight"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editProductInfo"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 供应商信息弹框 -->
    <el-dialog
      :title="titleType + '       供应商信息'"
      :visible.sync="providerDialogVisible"
      width="40%"
    >
      <p>供应商名称：{{ this.providerDetail.provider_name }}</p>
      <p>供应商货物：{{ this.providerDetail.provider_good }}</p>
      <p>供应商电话：{{ this.providerDetail.provider_phone }}</p>
      <p>供应商地址：{{ this.providerDetail.provider_address }}</p>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      // 商品列表
      goodsList: [],
      // 商品列表,不分页。所有商品信息
      goodsLists: [],
      //供应商列表，其中的供应商提供的商品字段给新增和修改时商品名称做下拉列表选项
      providersList: [],
      // 商品总数
      total: 0,
      // 控制添加商品对话框的显示与隐藏
      addDialogVisible: false,
      //添加分类弹框
      addCateDialogVisible: false,
      // 添加分类表单的数据对象
      addCateForm: {
        cate_name: '',
        // 父级分类的id
        cate_id: '',
        // 父级分类备注
        cate_remark: ''
      },
      // 添加分类表单验证规则
      addCateFormRules: {
        cate_name: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ],
        cate_id: [
          {
            required: true,
            message: '请输入分类ID',
            trigger: 'blur'
          },
          { type: 'number', message: '分类标识必须为数字值' }
        ]
      },
      // 添加用户的表单数据
      addForm: {
        productName: '',
        price: '',
        category: '',
        numbers: '',
        weight: '',
        pid: ''
      },
      //父级分类列表
      parentCateList: [],
      // 控制修改商品对话框的显示与隐藏
      editDialogVisible: false,
      //控制供应商信息对话框的显示与隐藏
      providerDialogVisible: false,
      //供应商表头
      titleType: '',
      //供应商具体信息
      providerDetail: {},
      //修改表单信息
      editForm: {},
      //修改表单的验证规则对象
      productRules: {
        productName: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        category: [
          {
            required: true,
            message: '请输入商品分类',
            trigger: 'blur'
          }
        ],
        numbers: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          },
          { type: 'number', message: '商品数量必须为数字值' }
        ],
        weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getGoodsList()
    this.getProvidersList()
  },
  methods: {
    // 根据分页获取对应的商品列表
    async getGoodsList() {
      //获取分页商品
      const { data: res } = await this.$http.get('allProduct', {
        params: this.queryInfo
      })
      if (res.numbers < 1) {
        return this.$message.error('获取商品列表失败！')
      }
      this.goodsList = res.data
      this.total = res.numbers
      //以下操作获取所有商品，和供应商信息作对比进行数据剔除
      const { data: res2 } = await this.$http.get('allProducts')
      this.goodsLists = res2.data
    },
    // 获取所有供应商信息
    async getProvidersList() {
      const { data: res } = await this.$http.get('allProviders')
      this.providersList = res.data
    },
    getProvider(name) {
      console.log(name)
      //表头赋值
      this.titleType = name
      //信息赋值
      for (let item of this.providersList) {
        if (item.provider_good == name) {
          this.providerDetail = item
          break
        }
      }
      console.log(this.providerDetail)
      //打开弹窗
      this.providerDialogVisible = true
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getGoodsList()
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize
      this.getGoodsList()
    },

    // 展示商品编辑的对话框
    async showEditDialog(id) {
      //获取父级分类
      this.getParentCateList()
      const { data: res } = await this.$http.get('getUpdateProduct?id=' + id)
      console.log(res)
      if (res == null) {
        return this.$message.error('查询商品信息失败！')
      }
      this.editForm = res
      this.editDialogVisible = true
    },
    // 监听添加商品对话框的关闭事件
    addDialogClosed() {
      // 重置表单项
      this.$refs.addFormRef.resetFields()
      //取消添加，对供应商数组还原
      this.getProvidersList()
    },
    // 监听对话框的关闭事件，重置表单数据
    addDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.addCateForm.cate_name = ''
      this.addCateForm.cate_id = ''
      this.addCateForm.cate_remark = ''
    },
    openAddForm() {
      //商品名数据做剔除操作
      //获取已存在商品名称拼接字符串
      var arr1 = ''
      for (let item of this.goodsLists) {
        arr1 += item.productName
      }
      //获取供应商供应货物列表
      var arr2 = []
      for (let item of this.providersList) {
        arr2.push(item.provider_good)
      }
      //判断供应商货物列表是否存在arr1中，不在则添加进arr3
      var arr3 = []
      for (let item of arr2) {
        console.log(item)
        if (arr1.indexOf(item) == -1) {
          arr3.push(item)
        }
      }
      //根据arr3构造合适的对象给list
      var list = []
      for (let i = 0; i < arr3.length; i++) {
        list.push({
          label: arr3[i],
          value: i
        })
      }
      //list赋值给展示数组，这时候供应商数组已被破坏，取消或添加商品应该对其还原
      this.providersList = list
      //打开窗口
      this.addDialogVisible = true
      //获取父级分类
      this.getParentCateList()
    },
    // 获取父级分类的数据列表,这里获取父级信息是为了给分类做option
    async getParentCateList() {
      const { data: res } = await this.$http.get('getFarherCatelogy')
      if (res.status !== 200) {
        return this.$message.error('获取父级分类数据失败!')
      }
      this.parentCateList = res.cates
      console.log('父级分类', this.parentCateList)
    },
    //添加商品
    addProduct() {
      //首先吧商品pid赋值准备用来传给后台
      for (let i = 0; i < this.parentCateList.length; i++) {
        if (this.addForm.category == this.parentCateList[i].cate_name) {
          this.addForm.pid = this.parentCateList[i].cate_id
        }
      }
      //发起添加商品请求
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('addProduct', this.addForm)
        if (res !== 'success') {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        // 隐藏添加商品对话框
        this.addDialogVisible = false
        // 重新获取商品列表数据
        this.getGoodsList()
        //还原供应商数组，避免再次打开添加页面出现错误
        this.getProvidersList()
      })
    },
    //修改商品信息并提交
    editProductInfo() {
      for (let item of this.parentCateList) {
        if (item.cate_name == this.editForm.category) {
          this.editForm.pid = item.cate_id
          this.editForm.category = item.cate_name
          break
        }
      }
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //发起修改商品信息的数据请求
        const { data: res } = await this.$http.put('editProduct', this.editForm)
        if (res !== 'success') {
          return this.$message.error('修改数据失败！')
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新商品数据列表
        this.getGoodsList()

        //提示修改成功
        this.$message.success('修改数据成功！')
      })
    },
    // 通过Id删除商品
    async removeById(product) {
      console.log(product, 'product')
      const { data: res2 } = await this.$http.get('allOrder', {
        params: {
          query: ''
        }
      })
      var orderList = res2.data
      console.log(orderList, 'orderList')
      for (let item of orderList) {
        if (product.productName == item.order_product) {
          return this.$message({
            showClose: true,
            message: '有订单包含该商品，无法删除',
            type: 'warning'
          })
        }
      }
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(
        'deleteProduct?id=' + product.productId
      )
      if (res !== 'success') {
        return this.$message.error('删除商品失败!')
      }
      this.$message.success('删除商品成功!')
      this.getGoodsList()
      this.getProvidersList()
    },
    // 点击按钮，添加新的分类
    addCate() {
      for (let item of this.parentCateList) {
        if (this.addCateForm.cate_id == item.cate_id) {
          return this.$message.error('标识id已存在！请修改')
        }
      }
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'addCatelogy',
          this.addCateForm
        )
        if (res !== 'success') {
          return this.$message.error('添加分类失败！')
        }
        this.$message.success('添加分类成功！')
        //获取父级分类
        this.getParentCateList()
        this.addCateDialogVisible = false
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
